package com.scau.wuwei.library_system.core.service.impl;

import com.scau.wuwei.library_system.core.bean.BookInfo;
import com.scau.wuwei.library_system.core.bean.BookInfoQuery;
import com.scau.wuwei.library_system.core.repository.BookInfoRepository;
import com.scau.wuwei.library_system.core.service.BookInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class BookInfoServiceImpl implements BookInfoService{

    @Resource
    private BookInfoRepository bookInfoRepository;

    //不需要查询条件
    @Override
    public Page<BookInfo> findBookNoCriteria(Integer page, Integer size) {
        Pageable pageable = new PageRequest(page, size, Sort.Direction.ASC, "bookId");
        return bookInfoRepository.findAll(pageable);
    }

    //需要查询条件

    @Override
    public Page<BookInfo> findBookCriteria(Integer page, Integer size, final BookInfoQuery bookInfoQuery) {
        Pageable pageable = new PageRequest(page, size, Sort.Direction.ASC, "bookId");
        Page<BookInfo> bookPage = bookInfoRepository.findAll(new Specification<BookInfo>(){
            @Override
            public Predicate toPredicate(Root<BookInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(null!=bookInfoQuery.getBookname()&&!"".equals(bookInfoQuery.getBookname())){
                    list.add(criteriaBuilder.equal(root.get("bookname").as(String.class), bookInfoQuery.getBookname()));
                }
                if(null!=bookInfoQuery.getAuthor()&&!"".equals(bookInfoQuery.getAuthor())){
                    list.add(criteriaBuilder.equal(root.get("author").as(String.class), bookInfoQuery.getAuthor()));
                }
                if(null!=bookInfoQuery.getPublisher()&&!"".equals(bookInfoQuery.getPublisher())){
                    list.add(criteriaBuilder.equal(root.get("publisher").as(String.class), bookInfoQuery.getPublisher()));
                }

                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        },pageable);
        return bookPage;
    }
}
